﻿using System;
using System.Configuration;
using System.Linq;
using System.Web.Caching;
using VerifyArgs;
using System.Data.SqlClient;

namespace EP.Caching.Attributes {
	[Serializable]
	[AttributeUsage(AttributeTargets.Class | AttributeTargets.Method | AttributeTargets.Property, Inherited = false, AllowMultiple = true)]
	sealed class SqlCacheExpiryAttribute : Attribute {
		#region Fields / Properties
		private readonly string _dsn;
		public string DSN { get { return _dsn; } }

		private readonly string _tableName;
		public string TableName { get { return _tableName; } }
		#endregion

		#region Constructor
		public SqlCacheExpiryAttribute(string dsn, string tableName) {
			Verify.Args(new { dsn, tableName }).NotNullOrEmpty();

			_dsn = dsn;
			_tableName = tableName;

			// TODO: check if dsn exists in config

			SetupSqlDependency();
		}
		#endregion

		private void SetupSqlDependency() {
			var connectionString = ConfigurationManager.ConnectionStrings[_dsn].ConnectionString;

			//SqlDependency.Start(connectionString);
			//SqlDependency.Stop(connectionString);

			SqlCacheDependencyAdmin.EnableNotifications(connectionString);
			if (!SqlCacheDependencyAdmin.GetTablesEnabledForNotifications(connectionString).Contains(_tableName)) {
				SqlCacheDependencyAdmin.EnableTableForNotifications(connectionString, _tableName);
			}
		}
	}
}
